package com.cgs.query.remote.http

import com.cgs.query.service.IQueryDefineService
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.web.client.RestTemplate

@Configuration

@Import(HttpClientConfiguration::class, HttpServiceConfiguration::class)
open class HttpConfiguration{

    @Bean
    @ConditionalOnMissingBean(RestTemplate::class)
    open fun consumerRestTemplate(builder: RestTemplateBuilder): RestTemplate = builder.build()

}

@Configuration
@ConditionalOnMissingBean(IQueryDefineService::class)
@ConditionalOnProperty(name = ["sql.runner.remote.type"], havingValue = "http", matchIfMissing = true)
open class HttpClientConfiguration {

    @Value("\${sql.runner.app.name:unknown}")
    private lateinit var appName: String

    @Value("\${sql.runner.remote.urls:}")
    private lateinit var urls: Array<String>

    @Bean
    open fun httpRemoteHandler(restTemplate: RestTemplate) = HttpRemoteHandler(restTemplate, urls).apply {
        hello(appName)
    }

}

@Configuration
@ConditionalOnBean(IQueryDefineService::class)
@Import(HttpRemoteController::class)
open class HttpServiceConfiguration{

    @Bean
    open fun serverRemoteHandler(restTemplate: RestTemplate) = HttpRemoteHandler(restTemplate, arrayOf())

}